package tgc.edu.examxy.web.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;

import tgc.edu.examxy.entity.TbMenu;
import tgc.edu.examxy.security.User2;
import tgc.edu.examxy.security.UserUtils;
import tgc.edu.examxy.custom.AjaxResult;
import tgc.edu.examxy.custom.DataGridParam;
import tgc.edu.examxy.custom.TimeUtils;
import tgc.edu.examxy.custom.VerifyCodeUtils;
import tgc.edu.examxy.custom.dict.entity.SystemData;
import tgc.edu.examxy.custom.dict.entity.TbClassType;
import tgc.edu.examxy.custom.dict.service.SystemDataService;
import tgc.edu.examxy.custom.dict.service.TbClassTypeService;
import tgc.edu.examxy.entity.ArticleManagement;
import tgc.edu.examxy.entity.Student;
import tgc.edu.examxy.entity.SysFile;
import tgc.edu.examxy.entity.SysRole;
import tgc.edu.examxy.entity.SysUser;
import tgc.edu.examxy.entity.TbClass;
import tgc.edu.examxy.service.ArticleManagementService;
import tgc.edu.examxy.service.MenuService;
import tgc.edu.examxy.service.StudentService;
import tgc.edu.examxy.service.SysFileService;
import tgc.edu.examxy.service.SysRoleService;
import tgc.edu.examxy.service.SysUserService;
import tgc.edu.examxy.service.TbClassService;
import tgc.edu.examxy.web.form.RegisterForm;
import tgc.edu.examxy.web.form.RegisterForm2;

@Controller
public class IndexController {
	@Autowired
	private TbClassService tbClassDAO;
	@Autowired
	private SysUserService userservice;
	@Autowired
	private StudentService studentservice;
	@Autowired
	private SysFileService fileservice;
	@Autowired
	private TbClassService tbClassService;
	@Autowired
	private SysRoleService sysRoleService;
	@Autowired
	private UserUtils userUtils;
	@Autowired
	private MenuService menuService;
	@Autowired
	private ArticleManagementService aservice;
	@Autowired
	private SystemDataService systemdataservice;
	@RequestMapping(value = "/aaa")
	public String che() {
		return "main/registeredsuccessfully";
	}
	
	@RequestMapping(value = { "/login", "/" }, method = RequestMethod.GET)
	public String login(ModelMap map) {
		/*String uuid = UUID.randomUUID().toString();
		VerifyCodeUtils code = new VerifyCodeUtils(160, 40, 4, 150);
		String path = "d:/" + uuid + ".png";
		try {
			System.out.println(code.getCode() + " >" + path);
			code.write(path);
		} catch (IOException e) {
			e.printStackTrace();
		}
		map.put("code", code.getCode());
		map.put("uuid", uuid);*/
		
		return "main/login";
	}



	@RequestMapping(value = "/main1")
	public String main1(ModelMap map) {
		List<ArticleManagement> a = aservice.findByType("学员须知");
		for (int i = 0; i < a.size(); i++) {
			String content = a.get(i).getContent();
			
			String replace = content.replace("/jeecgs/", "/jeecgxy/"); 
			a.get(i).setContent(replace);
		} 
		List<TbMenu> menus=menuService.findAuditMenu();
		map.put("idone", a.get(0).getId());
		map.put("menus",menus);
		map.put("xyxz", a);
		if(menus.isEmpty()) {
			return "main/main1";
		}
		
		return "main/main";
	}

	@Autowired
	private TbClassTypeService typeservice;
	/***
	 * 学员报名
	 * 跳转学员报名页面
	 * @return
	 */
	@RequestMapping(value = "/goXybm")
	public String goXybm(ModelMap map) {
		List<TbClassType> type = typeservice.findAll();
		map.put("type", type);
		return "main/xybm";
	}

	/***
	 * 学员注册 账号为身份证号码 密码为身份证后6位
	 * 
	 * @param form
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/toXybmsave")
	public Object toXybmsave(RegisterForm form, ModelMap map) {

		SysUser ifusernull = userservice.findByUsername(form.getIdcode());
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		if (ifusernull == null && form.getName() != null && form.getIdcode() != null) {
			Student studententity = new Student();
			String pwd = form.getIdcode();
			String password = pwd.substring(pwd.length() - 6, pwd.length());
			studententity.setUsername(form.getIdcode());
			studententity.setPassword(encoder.encode(password));
			studententity.setGroup1(false);
			studententity.setType("待审核");
			TbClass tbclassEntity = tbClassService.findById(UUID.fromString(form.getTbClassNmae()));
			
			String maxStudent = studentservice.maxStudent(tbclassEntity);
			String serical = tbClassService.serical(tbclassEntity,maxStudent);
			studententity.setSerial(serical);
			
			studententity.setTbClass(tbclassEntity);
			BeanUtils.copyProperties(form, studententity, "id");
			studentservice.saves(studententity);
			fileservice.DeleteAll(form.getFileuuid());
			map.put("username", form.getIdcode());
			map.put("password", password);
			return "main/registeredsuccessfully";
		} else {
			Student students = studentservice.findById(ifusernull.getId());
			if(students.getType().equals("已通过")) {
				return "main/login";
			}
			students.setName(form.getName());
			students.setSex(form.getSex());
			students.setNation(form.getNation());
			students.setBron(form.getBron());
			students.setPolitics(form.getPolitics());
			students.setDegree(form.getDegree());
			students.setSpeciality(form.getSpeciality());
			students.setWorkUnit(form.getWorkUnit());
			students.setJob(form.getJob());
			students.setJobLevel(form.getJobLevel());
			students.setOfficetel(form.getOfficetel());
			students.setPhone(form.getPhone());
			students.setAddress(form.getAddress());
			students.setPostalCode(form.getPostalCode());
			students.setIsimmigrant(form.getIsimmigrant());
			students.setFileuuid(form.getFileuuid());
			
			if(students.getType().equals("已通过")) {
				//保存原来班级的ID
				students.setTbClassid(students.getTbClass().getId());
			}
			//将用户状态改为待审核
			students.setType("待审核");
			//清空这个用户的权限
			students.setRoles(null);
			students.setGroup1(false);
			//保存新选择的班级
			TbClass tbclassEntity = tbClassService.findById(UUID.fromString(form.getTbClassNmae()));
			
			String maxStudent = studentservice.maxStudent(tbclassEntity);
			String serical = tbClassService.serical(tbclassEntity,maxStudent);
			students.setSerial(serical);
			students.setTbClass(tbclassEntity);
			studentservice.save(students);
			map.put("username", form.getIdcode());
			return "main/registeredsuccessfully";
		}
	}
	
	

	/****
	 * 调取数据字典
	 * @return
	 */
	@RequestMapping(value="/dict")
	@ResponseBody
	private Object dict(String code) {
		Order order=new Order(Direction.fromString("ASC"), "createDate");
		Sort sort=Sort.by(order);
		List<SystemData> findBySystemDictionariesCode = systemdataservice.findBySystemDictionariesCode(code,sort);
		 
		return findBySystemDictionariesCode;
	}
	
	
	/***
	 * 注册 用户上传图片
	 * 
	 * @param file
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/toFilesave")
	@ResponseBody
	private Object toFilesave(MultipartFile file, ModelMap map) {
		String uuid = UUID.randomUUID().toString();
		boolean boole = fileservice.savefile(file, uuid);
		if (boole) {
			return new AjaxResult(true, uuid);
		} else {
			return new AjaxResult(true, file.getOriginalFilename());
		}

	}

	/***
	 * 下载图片
	 * 
	 * @param uuid
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/download")
	@ResponseBody
	private void download(String uuid, HttpServletRequest request, HttpServletResponse response) {
		if("null".equals(uuid)){
			fileservice.download2(uuid, request, response);
		}else {
			fileservice.download(uuid, request, response);
		}
	}
	/***
	 * 下载课件资源
	 * 
	 * @param uuid
	 * @param request
	 * @param response
	 * @return 
	 */
	@RequestMapping(value = "/downloadfile")
	@ResponseBody
	private boolean downloadfile(String uuid, HttpServletRequest request, HttpServletResponse response) {
		SysFile fileentity = fileservice.findByUuid(uuid);
		if(fileentity==null) {
			return false;
		}else {
			File file = new File(fileentity.getStoreaddress(), uuid);
			if(file.exists()) {
				return true;				
			}else {
				return false;
			}
		}
	}
	/***
	 * 注册 主体班学员 专题班学员
	 * @param value
	 * @return
	 */
	@RequestMapping(value = "/totbClass")
	@ResponseBody
	private Object tbClass(String value) {
		List<TbClass> tbclasslist = tbClassService.findByTbClassName(value);
		List<RegisterForm2> tb = new ArrayList<>();
		for (TbClass tbClass : tbclasslist) {
			boolean ifTime = tbClassService.ifTime(tbClass);// 判断当前的时间
			if (ifTime) {
				RegisterForm2 res = new RegisterForm2();
				res.setId(tbClass.getId());
				res.setName(tbClass.getName());
				tb.add(res);
			}
		}
		return tb;
	}

	@RequestMapping(value = "/toTime")
	@ResponseBody
	private Object TbClassTime(String uuid) {
		String list = tbClassService.findByTime(UUID.fromString(uuid));
		return list;
	}
	@RequestMapping(value="/changePwd",method=RequestMethod.GET)
	public String changePwd() {
		return "main/changePwd";
	}
	
	@RequestMapping(value="/changePwd",method=RequestMethod.POST)
	@ResponseBody
	public Object changePwd(String oldPwd,String newPwd) {
		BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
		SysUser user = userUtils.getUser();
		String password = user.getPassword();
		if(!encoder.matches(oldPwd, password)) {
			return new AjaxResult(false, "旧密码不正确！");
		}
		user.setPassword(encoder.encode(newPwd));
		userservice.save(user);
		return new AjaxResult("密码修改成功");
	}
	
	@RequestMapping(value = "/goidcode")
	@ResponseBody
	public Object goidcode(String idcode) {
		if(idcode!=null&&idcode!="") {
			Student studententity = studentservice.findByUsername(idcode);
			if(studententity!=null) {
				return studententity;
			}
		}
		return null;
	}
	
	@RequestMapping(value ="/index")
	private String index(ModelMap map) {
		SecurityContext ctx = SecurityContextHolder.getContext();
		Authentication auth = ctx.getAuthentication();
		User2 user = (User2) auth.getPrincipal();
		Student student = studentservice.findByUsername(user.getUsername());
		if(student!=null) {
			String type = student.getType();
			if(type.equals("已拒绝")) {
				map.put("student", student);
			}
		}
		return "main/index";
	}
	//-------------分割线 验证码----------------------------------------------
	
	/***
	 * 验证码部分
	 * @param request
	 * @param fileName
	 * @return
	 */
	private String getStr(HttpServletRequest request, String fileName) {
		String downloadFileName = null;
		// 仅提供了部分代码，因为我们已经明确问题的所在，知道修改那一部分了，（代码中downloadFileName 即代表
		// *=utf-8'zh_cn'文件名.xx部分）
		String agent = request.getHeader("USER-AGENT");
		try {
			if (agent != null && agent.toLowerCase().indexOf("firefox") > 0) {
				// downloadFileName = "=?UTF-8?B?" + (new
				// String(Base64Utils.encode(fileName.getBytes("UTF-8")))) + "?=";
				// 设置字符集
				downloadFileName = "=?UTF-8?B?" + Base64Utils.encodeToString(fileName.getBytes("UTF-8")) + "?=";
			} else {
				downloadFileName = java.net.URLEncoder.encode(fileName, "UTF-8");
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return downloadFileName;
	}

	/*@RequestMapping(value = "/verify")
	@ResponseBody
	public Object Verify() {
		Map<String, String> map = new HashMap<>();
		String uuid = UUID.randomUUID().toString();
		VerifyCodeUtils code = new VerifyCodeUtils(160, 40, 4, 150);
		String path = "d:/" + uuid + ".png";
		StringBuffer sb = new StringBuffer();
		sb.append("{");
		sb.append("\"code\":\"" + code.getCode() + "\",");
		sb.append("\"uuid\":\"" + uuid + "\"");
		sb.append("}");
		JSONObject result = JSONObject.parseObject(sb.toString()); 
		String data = result.toJSONString(); 
		try {
			System.out.println(code.getCode() + " >" + path);
			code.write(path);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return data;
	}*/

	/*@RequestMapping(value = "/verifyCode")
	@ResponseBody
	private void VerifyCode(String uuid, HttpServletRequest request, HttpServletResponse response) {
		String filename = uuid + ".png";
		filename = getStr(request, filename);
		File file = new File("d:/" + uuid + ".png");
		if (file.exists()) {
			FileInputStream fis;
			try {
				fis = new FileInputStream(file);
				response.setContentType("application/x-msdownload");
				response.addHeader("Content-Disposition", "attachment; filename=" + filename);
				ServletOutputStream out = response.getOutputStream();
				byte[] buf = new byte[2048];
				int n = 0;
				while ((n = fis.read(buf)) != -1) {
					out.write(buf, 0, n);
				}
				fis.close();
				out.flush();
				out.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}*/
}
